/*
 * Copyright (c) 2006, 2021, webrx.cn All rights reserved.
 *
 */
package cn.webrx.config;


import org.springframework.context.annotation.Configuration;
import org.springframework.core.SpringVersion;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.stereotype.Controller;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
import java.nio.charset.Charset;
import java.util.List;

/**
 * <p>Project: springmvc2021 - WebInit
 * <p>Powered by webrx On 2021-11-04 11:47:08
 * <p>Created by IntelliJ IDEA
 *
 * @author webrx [webrx@126.com]
 * @version 1.0
 * @since 17
 */

@EnableWebMvc @RestController @Configuration
public class WebInit implements WebApplicationInitializer, WebMvcConfigurer {

    @Override
    public void onStartup(ServletContext sctx) throws ServletException {
        var ctx = new AnnotationConfigWebApplicationContext();
        ctx.register(this.getClass());
        ctx.setServletContext(sctx);
        ServletRegistration.Dynamic servlet = sctx.addServlet("dispatcher", new DispatcherServlet(ctx));
        servlet.addMapping("/");
        servlet.setLoadOnStartup(1);
    }


    public void configureMessageConverters(List<HttpMessageConverter<?>> c) {
        var cs = Charset.forName("utf-8");
        var shmc = new StringHttpMessageConverter();
        shmc.setDefaultCharset(cs);
        var list = List.of(MediaType.parseMediaType("text/html;charset=UTF-8"));
        shmc.setSupportedMediaTypes(list);
        c.add(shmc);
    }

    @GetMapping("/")
    public String hello(){
        return String.format("hello world 中文效果 [springmvc %s]", SpringVersion.getVersion());
    }
}
